import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {Module} from '../entity/Module.model';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class ModuleService {
  private param = 'basicModule';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {

  }

  /**
   * 获得风机状态
   *
   * @returns {Promise<TurbStatus[]>}
   * @memberof TurbStatusService
   */
  getBaiscModule(): Promise<Module[]> {
    return this.http.get(`${this.url}/all`)
      .toPromise()
      .then(response => {
        return response.code === '200' ? response.data as Module[] : [];
      }).catch(this.handleError);
  }


  create(module: Module): Promise<Module> {
    return this.http
      .post(this.url, JSON.stringify(module))
      .toPromise()
      .then(res => res.code === '200' ? res.data : [])
      .catch(this.handleError);
  }

  update(module: Module): Promise<Module> {
    const url = `${this.url}`;
    return this.http
      .put(url, JSON.stringify(module))
      .toPromise()
      .then(() => module)
      .catch(this.handleError);
  }

  delete(id: number): Promise<any> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}
